package main

import (
	"fmt"
	"log"
	"os"
	"net/http"
	"html/template"
)

type Page struct {
	Title string
	Body []byte
}

// Use os

func (p *Page) save() error {
	fileName := "./post/" + p.Title + ".html"
	return os.WriteFile(fileName, p.Body, 0600)	//0600是一个八进制整数，这里用它来表示权限，具体权限可以参考Unix下的文件权限说明
}

func loadPage(title string) (*Page, error) {
	fileName := "./post/" + title + ".html"
	body, err := os.ReadFile(fileName)
	if err != nil {
		return nil, err
	}
	return &Page{Title: title, Body: body}, nil
}

// Use net/http

func handler(w http.ResponseWriter, r *http.Request) {
	f, _ := os.Open("./post")
	list, _ := f.Readdir(-1)
	f.Close()
	fmt.Println(list)
	fmt.Fprintf(w, list)
	
}

func viewHandler(w http.ResponseWriter, r *http.Request) {
	title := r.URL.Path[len("/view/"):]
	p, err := loadPage(title)
	if err != nil {
		http.Redirect(w, r, "/edit/"+title, http.StatusFound)
		return
	}
	renderTemplate(w,"view",p)
}

func editHandler(w http.ResponseWriter, r *http.Request) {
	title := r.URL.Path[len("/edit/"):]
	p, err := loadPage(title)
	if err != nil {
		p = &Page{Title: title}
	}
	// fmt.Fprintf(w, "<h1>%s</h1><div>"+
	// 	"<form action=\"/save/%s\" method=\"POST\">"+
	// 	"<textarea name=\"body\">%s</textarea><br>"+
	// 	"<input type=\"submit\" value=\"Save\">"+
	// 	"</form>"+
	// 	"</div>",p.Title, p.Title, p.Body)
	renderTemplate(w,"edit",p)
}

func saveHandler(w http.ResponseWriter, r *http.Request) {
	title := r.URL.Path[len("/save/"):]
	body := r.FormValue("body")
	p := &Page{Title: title, Body: []byte(body)}
	p.save()
	http.Redirect(w, r, "/view/"+title, http.StatusFound)
}

func renderTemplate(w http.ResponseWriter, templ string, p *Page) {
	t, _ := template.ParseFiles(templ + ".html")
	t.Execute(w, p)
}


func main() {
	// p1 := &Page{Title: "TestPage", Body: []byte("This is a simple Page.")}
	// p1.save()
	// p2, _ := loadPage("TestPage")
	// fmt.Println(string(p2.Body))

	http.HandleFunc("/", handler)
	http.HandleFunc("/view/", viewHandler)
	http.HandleFunc("/edit/", editHandler)
	http.HandleFunc("/save/", saveHandler)
	log.Fatal(http.ListenAndServe(":8080", nil))
}